package ru.smc.hogwarts.servlets.messages;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Message;
import ru.smc.hogwarts.model.Person;

public class MessagesDelete extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
    	session.setAttribute("servletName", getServletName());
    	EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
    	int id = 0;
   		int uid = (Integer)session.getAttribute("userID");
//    	if (id!=0){
//			sender=em.find(Person.class, id);
//			request.setAttribute("sender", sender);
//		}
    	
    	try{
	    	id = Integer.parseInt(request.getParameter("id"));
	    	Query query = em.createQuery("select p from Message p where (p.sender.id=?1 or p.recipient.id =?1) and p.id =?2");
	    	query.setParameter(1, uid);
	   		query.setParameter(2, id);
	   		query.getSingleResult();
   		}
   		catch(Exception e){
   		}
   		
		Message message = em.find(Message.class, id);
		em.getTransaction().begin();
		Person resipient = message.getRecipient();
		if (resipient.getId()==uid) {
			message.setDeletetedr(true);
		}
		Person sender = message.getSender();
		if (sender.getId()==uid) {
			message.setDeleteteds(true);
		}
		if (message.getDeleteteds() && message.getDeletetedr()) {
			em.remove(message);
		}
		em.getTransaction().commit();
		em.close();
		response.sendRedirect(request.getContextPath() + "/messages");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
